package com.xored.glance.internal.ui;

import java.net.URL;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class GlancePlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "com.xored.glance.ui";

	// IMAGES

	private static final String IMG_PREFIX = "icons/";

	public static final String IMG_NEXT = IMG_PREFIX + "next.gif";
	public static final String IMG_PREV = IMG_PREFIX + "prev.gif";
	public static final String IMG_SEARCH = IMG_PREFIX + "search.png";

	// The shared instance
	private static GlancePlugin plugin;

	/**
	 * The constructor
	 */
	public GlancePlugin() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static GlancePlugin getDefault() {
		return plugin;
	}

	public static Image createImage(String path) {
		ImageDescriptor image = getImageDescriptor(path);
		if (image != null)
			return image.createImage();
		return null;
	}

	public static ImageDescriptor getImageDescriptor(String path) {
		ImageDescriptor image = getDefault().getImageRegistry().getDescriptor(
				path);
		if (image == null) {
			image = ImageDescriptor.createFromURL(makeImageURL(path));
			getDefault().getImageRegistry().put(path, image);
		}
		return image;
	}

	public static void log(Throwable t) {
		logError(t.getMessage(), t);
	}

	public static void logError(String message, Throwable t) {
		getDefault().getLog().log(
				new Status(Status.ERROR, PLUGIN_ID, message, t));
	}

	public static void logWarning(String message) {
		getDefault().getLog().log(
				new Status(Status.WARNING, PLUGIN_ID, message));
	}

	private static URL makeImageURL(String path) {
		return FileLocator.find(getDefault().getBundle(), new Path(path), null);
	}
}
